//
//  OSSApi.swift
//  skincare
//
//  Created by whu125 on 2023/5/12.
//

import Moya

enum OSSApi {
    case uploadImage(image: UIImage, policy: String, accessKeyId: String, signature: String, dir: String, host: String, expire: String)
}

extension OSSApi: TargetType {
    var baseURL: URL {
        guard let url = URL(string: "https://fun-skincare.oss-cn-shanghai.aliyuncs.com") else {
            fatalError("Invalid endpoint")
        }
        return url
    }
    
    var path: String {
        return ""
    }
    
    var method: Method {
        return .post
    }
    
    var sampleData: Data {
        return Data()
    }
    
    var task: Task {
        switch self {
            case let .uploadImage(image, policy, accessKeyId, signature, dir, host, expire):
              let imageData = image.jpegData(compressionQuality: 0.5)!
              let fileName = "\(dir)/\(UUID().uuidString).jpg"
              
              let formData: [MultipartFormData] = [
                MultipartFormData(provider: .data(policy.data(using: .utf8)!), name: "policy"),
                MultipartFormData(provider: .data(accessKeyId.data(using: .utf8)!), name: "OSSAccessKeyId"),
                MultipartFormData(provider: .data(signature.data(using: .utf8)!), name: "Signature"),
                MultipartFormData(provider: .data(expire.data(using: .utf8)!), name: "expire"),
                MultipartFormData(provider: .data(host.data(using: .utf8)!), name: "host"),
                MultipartFormData(provider: .data(fileName.data(using: .utf8)!), name: "key"),
                MultipartFormData(provider: .data(imageData), name: "file", fileName: fileName, mimeType: "image/jpeg")
              ]
              
              return .uploadMultipart(formData)
            }
    }
    
    var headers: [String : String]? {
        return ["Content-Type": "multipart/form-data"]
    }
}

let oss_Provider = MoyaProvider<OSSApi>()
